// pages/register/register.js
const apiurl = require('../../config').apiurl;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    uid: '',
    clicked: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var uid = options.uid ? options.uid : '';
    var ro_id = options.ro_id ? options.ro_id : '';
    console.log('uid', uid);
    wx.setStorageSync('uid', uid);
    this.setData({
      uid,
      ro_id
    })
    // 载入登录页时，清空缓存数据key
    if (wx.getStorageSync('key')) {
      wx.removeStorageSync('key');
      wx.removeStorageSync('member_id');
      wx.removeStorageSync('member_name')
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {


  },
  bindGetUserInfo(e) {
    if (this.data.clicked) {
      wx.showModal({
        title: '提示',
        content: '请勿重复点击哦~',
        showCancel: false
      })
      return;
    }
    this.getUsers();
  },

  getUsers() {
    console.log("uid", this.data.uid);

    wx.showLoading({
      title: '登录中...'
    })
    var that = this;
    // 查看是否授权
    wx.getSetting({
      success: (res) => {
        console.log("getSetting", res)
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) {
              console.log("getUserInfo", res)
              wx.login({
                success: function(a) {
                  console.log("code", a.code)
                  // 发送 res.code 到后台换取 openId, sessionKey, unionId
                  if (a.code) {
                    console.log("uid", that.options.uid + '....')
                    let params = {};
                    params.code = a.code;
                    params.iv = res.iv;
                    // params.iv="dmCUdSgP05XXUyVKTG//3g=="
                    params.encryptedData = res.encryptedData;
                    params.uid = wx.getStorageSync('uid')
                    console.log("register_params", params)
                    wx.request({
                      url: apiurl + '/login/login', //仅为示例，并非真实的接口地址
                      data: params,
                      method: 'POST',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      success: function(resl) {
                        console.log("resl", resl)
                        if (resl.data.code == 200) {
                          // 避免重复点击
                          that.setData({
                            clicked: true
                          })

                          wx.setStorageSync("key", resl.data.datas.key);
                          wx.setStorageSync("member_id", resl.data.datas.member_id);
                          wx.setStorageSync("member_name", resl.data.datas.member_name);
                          // 如果是红包分享页，注册成功跳到拆红包页面
                          let ro_id = that.data.ro_id;
                          console.log("ro_id", ro_id)
                          wx.hideLoading();
                          if (ro_id) {
                            console.log("跳转到红包页面")
                            wx.reLaunch({
                              url: '/pages/envelopes/envelopes?ro_id=' + ro_id
                            });
                          } else {
                            wx.reLaunch({
                              url: "../index/index"
                            });
                          }

                        }
                        if (resl.data.code == 400) {
                          // 注册失败时清空缓存key  重新拉起登录
                          wx.removeStorageSync('key');
                          wx.removeStorageSync('member_id');
                          wx.removeStorageSync('member_name');

                          wx.showModal({
                            title: '提示',
                            content: '注册失败',
                            showCancel: false,
                            success: function(res) {
                              wx.hideLoading();
                              if (res.confirm) {
                                wx.reLaunch({
                                  url: "../register/register?uid=" + wx.getStorageSync('uid')
                                });
                              }
                            }
                          })
                        }


                      }
                    })
                  } else {
                    console.log('获取用户登录态失败！' + res.errMsg)
                  }
                }
              })

            }
          })
        } else {
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: '获取用户信息失败,需要授权才能继续使用！',
            confirmText: '授权',
            showCancel: !1,
            success: data => {
              data.confirm && wx.openSetting({
                success: data => {
                  data.authSetting["scope.userInfo"] ? wx.showToast({
                    title: "授权成功"
                  }) : wx.showToast({
                    title: "未授权..."
                  });
                }
              })
            }
          })
        }
      }
    })
  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})